/**
* Device.js controlador para la vista imagecamera.
* Aqui se declaran los eventos utilizados
* en el aplicativo.
*/
Ext.define("entgpv11.controller.Device", {
    extend: "Ext.app.Controller",
    config:
    {
        refs:
        {
            carousel: "imagelist",
            camera: "imagecamera",
            details: "details"
        },
        control:
        {
            camera:
			 {
			     show: "onCaptureImagen",
			     backButtonTapCommand: "onBackButtonTap",
			     captureCommand: "onCaptureImagen",
			     saveButtonTapCommand: "onSaveButtonTap",
			     deleteButtonTapCommand: "onDeleteButtonTap",
			    
			 }
        }
    },



    // Transitions
    slideLeftTransition: { type: 'slide', direction: 'left' },
    /**
     * Elimina el primer y unico item del store imagenes
     * 
     */
    removeItemStore: function () {
        try {
            var myStore = Ext.getStore('Images');
            var n = myStore.getCount();
            if (n == 1) {
                myStore.removeAt(0);
            }
            return (myStore);
        } catch (ex) {
            APP_GLOBAL.SetLog('removeItemStore::' + ex);
        }
    },
     /**
     * Retorna el primer registro del store imagenes
     * 
     */
    getItemStore: function () {
        try {
            var myStore = Ext.getStore('Images');
            var record = null;
            var n = myStore.getCount();
            if (n == 1) {
                record = myStore.getAt(0);
            }
            return (record);
        } catch (ex) {
            APP_GLOBAL.SetLog('removeItemStore::' + ex);
        }
    },
     /**
     * Oculta o muestra actions view segun variable booleana val
     * @param val.
     * @param type.
     */
    setHiddenButtons: function (val, type) {
        try {
            this.getCamera().actions_view(val);
        } catch (ex) {
            APP_GLOBAL.SetLog(' setHiddenButtons::' + ex);
        }
    },
    /**
     * @private
     * @param fn
     * @param scope
     */
    goExit: function () {
        try {
            this.setHiddenButtons(false, 1);
            var tabs = Ext.getCmp('tabDetails');
            tabs.setActiveItem(2);
            var formback = this.getDetails();
            Ext.Viewport.animateActiveItem(formback, this.slideLeftTransition);
        } catch (ex) {
            APP_GLOBAL.SetLog(' goExit::' + ex);
        }
    },
     /**
    * The device API returns a URI for the image, so lets add that into the image list store
    */
    /*
    onCaptureSuccess: function (uri) {
    try {


    var myStore = this.removeItemStore();
    myStore.add({ src: uri });
    this.setHiddenButtons(true, 1);

    } catch (ex) {
    APP_GLOBAL.SetLog(' onCaptureSuccess::' + ex);
    }
    },
    */
    onCaptureSuccess: function (data) {
        try {
            
            var record = new entgpv11.model.Images();
            if (data=='http://www.sencha.com/img/sencha-large.png')
               data ='iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAADCklEQVRoBe2YPWgUQRiGb038gagBxUIR1CaNRRAklQgWVv4UVoqNiHUKWxFFBH8bCYiVnZ1orbEUAoLYiMZCLURBVKJEOEVz5/Mqs2xub3dn3du9u9n54L3ZnZlv5nvnnb+9oN1uN+pkK+pEVlw9YdcV9wp7hR0bAT+lHRM0RscrHBsSxzK8wo4JGqMTkCO4qnSLj6NlX0ejkN0MpoBrJqLPwetOYkfIUKFrWILTtASOwtWpLFGXTWVlyFwm/I9hx2/tCGvT6mYtMheA1sGw2CYC1YmTakmEv+F1FXwEmY2k9lBd4Q26Wp/VXRLh7zjeZXd7k9XAoJQHQXCFWGKEyR+Fx28TZxJhqRqW4TTG+0rjlCNdpLN+LQvtT3vAU+J/SdoklmZIKoPEcconQdetPsFXdW/T2Qs6+plQp8xsiXYY7AJzYJZYHpE2ul083pE/QaB/D22e7wNNi7zQTecEGDNtlZXSh/abtMvTV8rnbRXW9BgBeW0nDufBD0b3AWS18/fLxul43PYczjOVOwltI+MyOAbpjZ2FVb/bEi4al0ifASchvbVoY0X8qyKsGLeAi+AWpPeBvpzvtmtYAffCVtHIfqBj7hec51jXlR5bVSpsBkyk94Kz4CCk15iCKtKqFTacNNBSegMYgfQsSi+awjLTfihs+GgN7wYz4BqkJ0xBmWk/CRte2syOgguQ3k5aqg0CYRHUpeAAuATpHcooy2wJ/88tK2/Ma3E4BGYgPQVsY8vTT8t20/pMqx/ytFyg7iS+58Bp8KpAO1HXJi/z4Ikt4ZtUvhdtoYLnXij8iTgfA30lPQRfbAk/o3IvAqAZK9MOrr+Zipj874DrYAHoe7idRphlFF7/dBuq9EZEf41I/3rNa/rgeQvH91HHJMLrqHQKaO1qtIfBdF3NtCTCOiamgUZpWGy1TaBJhOWrO69zVuVGNBCD5wkPhAwlBqEdWNfGtLVcYvelN73EsaR/WkMLyAhf6vDg17DrKnuFvcKOjYCf0o4JGqPjFY4NiWMZXmHHBI3RqZ3CfwB9oSaHHrORiQAAAABJRU5ErkJggg==';
       
            record.data.picture = 'data:image/png;base64,' + data;
            record.data.data = data;
            var myStore = this.removeItemStore();
            myStore.add(record);
            myStore.sync();

            this.setHiddenButtons(true, 1);

        } catch (ex) {
            APP_GLOBAL.SetLog(' onCaptureSuccess::' + ex);
        }
    },

    // Commands.
    /**
    *    CAMERA:
    *			 {
    *			     show: "onCaptureImagen",
    *			     backButtonTapCommand: "onBackButtonTap",
    *			     captureCommand: "onCaptureImagen",
    *			     saveButtonTapCommand: "onSaveButtonTap",
    *			     deleteButtonTapCommand: "onDeleteButtonTap",
    *			    
    *			 }
    */
    
     /**
     * Captura la imagen con el dispositivo.
     * Si se esta utilizando el navegador se muestra una imagen por defecto
     * 
     */
    onCaptureImagen: function () {
        try {
            
          
            Ext.device.Camera.capture({
                success: this.onCaptureSuccess,
                scope: this,
                source: 'camera',
                destination: 'data'
            });

        }
        catch (ex) {
            APP_GLOBAL.SetLog("onCaptureImagen..." + ex);
            this.onCaptureSuccess('iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAADCklEQVRoBe2YPWgUQRiGb038gagBxUIR1CaNRRAklQgWVv4UVoqNiHUKWxFFBH8bCYiVnZ1orbEUAoLYiMZCLURBVKJEOEVz5/Mqs2xub3dn3du9u9n54L3ZnZlv5nvnnb+9oN1uN+pkK+pEVlw9YdcV9wp7hR0bAT+lHRM0RscrHBsSxzK8wo4JGqMTkCO4qnSLj6NlX0ejkN0MpoBrJqLPwetOYkfIUKFrWILTtASOwtWpLFGXTWVlyFwm/I9hx2/tCGvT6mYtMheA1sGw2CYC1YmTakmEv+F1FXwEmY2k9lBd4Q26Wp/VXRLh7zjeZXd7k9XAoJQHQXCFWGKEyR+Fx28TZxJhqRqW4TTG+0rjlCNdpLN+LQvtT3vAU+J/SdoklmZIKoPEcconQdetPsFXdW/T2Qs6+plQp8xsiXYY7AJzYJZYHpE2ul083pE/QaB/D22e7wNNi7zQTecEGDNtlZXSh/abtMvTV8rnbRXW9BgBeW0nDufBD0b3AWS18/fLxul43PYczjOVOwltI+MyOAbpjZ2FVb/bEi4al0ifASchvbVoY0X8qyKsGLeAi+AWpPeBvpzvtmtYAffCVtHIfqBj7hec51jXlR5bVSpsBkyk94Kz4CCk15iCKtKqFTacNNBSegMYgfQsSi+awjLTfihs+GgN7wYz4BqkJ0xBmWk/CRte2syOgguQ3k5aqg0CYRHUpeAAuATpHcooy2wJ/88tK2/Ma3E4BGYgPQVsY8vTT8t20/pMqx/ytFyg7iS+58Bp8KpAO1HXJi/z4Ikt4ZtUvhdtoYLnXij8iTgfA30lPQRfbAk/o3IvAqAZK9MOrr+Zipj874DrYAHoe7idRphlFF7/dBuq9EZEf41I/3rNa/rgeQvH91HHJMLrqHQKaO1qtIfBdF3NtCTCOiamgUZpWGy1TaBJhOWrO69zVuVGNBCD5wkPhAwlBqEdWNfGtLVcYvelN73EsaR/WkMLyAhf6vDg17DrKnuFvcKOjYCf0o4JGqPjFY4NiWMZXmHHBI3RqZ3CfwB9oSaHHrORiQAAAABJRU5ErkJggg==');
        }
    },


    onBackButtonTap: function () {
        try {
            this.goExit();
        } catch (ex) {
            APP_GLOBAL.SetLog(' onBackButtonTap::' + ex);
        }
    },
    
     /**
     * Graba la imagen capturada con el dispositivo
     * @me
     * 
     */
    onSaveButtonTap: function (me) {
        try {
           
             Ext.Viewport.setMasked({
                    xtype: 'loadmask',
                     message: 'Enviando..',
                    indicator: false
                });
            var recordImg = this.getItemStore();
            if (recordImg != null) {
                var jsonFile = {
                    id: this.getDetails().getDataId(),
                    myData: recordImg.get('data')
                };

                Ext.Ajax.request({
                    url: Ext.APP_GLOBAL.getServiceUrl() + 'SetResources',
                    disableCaching: false,
                    scriptTag: true,
                    methode: 'POST',
                    params: jsonFile,
                    success: function (response, opts) {
                        
                        this.removeItemStore();
                        this.getCarousel().addItem(recordImg.get('data'));
                         Ext.Viewport.unmask();
                        this.goExit();
                       
                    },
                    failure: function (response, opts) {
                        console.log('server-side failure with status code ' + response.status);
                        this.removeItemStore();
                        Ext.Viewport.unmask();
                        Ext.Msg.alert('Error', 'Los datos no pueden ser enviados', Ext.emptyFn);
                        this.setHiddenButtons(false, 1);
                       
                    },

                    scope: this


                });
            }
        } catch (ex) {
            APP_GLOBAL.SetLog(' onSaveButtonTap::' + ex);
        }

    },
     /**
     * Remueve la imagen de la pre-vizualicion con la camara
     * @me
     * 
     */
    onDeleteButtonTap: function (me) {
        try {
            this.removeItemStore();
            this.goExit();
        } catch (ex) {
            APP_GLOBAL.SetLog(' onDeleteButtonTap::' + ex);
        }
    },
   
    // Base Class functions.
    launch: function () {
        this.callParent(arguments);
    },
    init: function () {
        this.callParent(arguments);
    }
});
